package org.hdax.dm.rest.service;

import org.hdax.dm.dao.entitydao.DmCinemaDao;
import org.hdax.dm.entity.cinema.DmCinema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@RestController
public class RestDmCinemaService {
    @Autowired
    private DmCinemaDao dmCinemaDao;

    @PostMapping(path = "/findByDmCinema")
    public List<DmCinema> findByDmCinema(@RequestBody DmCinema dmCinema) {
        return dmCinemaDao.findAll(where(dmCinema));
    }

    public Specification<DmCinema> where(DmCinema dmCinema) {
        return new Specification<DmCinema>() {
            @Override
            public Predicate toPredicate(Root<DmCinema> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (dmCinema != null) {
                    if (dmCinema.getId() != null && dmCinema.getId() > 0) {
                        predicateList.add(criteriaBuilder.equal(root.get("id").as(Integer.class), dmCinema.getId()));
                    }
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
            }
        };
    }
}
